package censor

import (
	"context"
	"fmt"
	"gitee.com/mootok/mootok/src/constant/config"
	"github.com/qiniu/go-sdk/v7/auth"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/client"
)

type QiniuService struct {
	mac *qbox.Mac
}

func (f *QiniuService) CreateAuditVideoTask(path string) (string, error) {
	reqUrl := "https://ai.qiniuapi.com/v3/video/censor"

	//构造七牛云请求body
	params := map[string]interface{}{
		"data": map[string]interface{}{
			"uri": "qiniu:///" + config.EnvConfig.QiNiuKodoBucket + "/" + path,
		},
		"params": map[string]interface{}{
			"scenes": []string{"pulp", "terror", "politician"},
			"cut_param": map[string]interface{}{
				"interval_msecs": 5000,
			},
		},
	}

	//发送请求
	var ret map[string]string
	err := client.DefaultClient.CredentialedCallWithJson(context.Background(), f.mac, auth.TokenQiniu, &ret, "POST", reqUrl, nil, params)
	if err != nil {
		return "", err
	}

	jobId := ret["job"]
	return jobId, nil
}

func (f *QiniuService) QueryAuditVideoTaskProgress(jobId string) (status Status, result Result, err error) {
	reqUrl := "https://ai.qiniuapi.com/v3/jobs/video/" + jobId

	//构造七牛云请求body
	params := map[string]interface{}{
		"job_id": jobId,
	}

	//发送请求
	var ret map[string]interface{}
	err = client.DefaultClient.CredentialedCallWithJson(context.Background(), f.mac, auth.TokenQiniu, &ret, "GET", reqUrl, nil, params)
	if err != nil {
		return -1, -1, err
	}
	retStatus := ret["status"].(string)

	if retStatus == "WAITING" {
		status = StatusWaiting
	} else if retStatus == "FINISHED" {
		status = StatusFinished
	} else if retStatus == "RESCHEDULED" {
		status = StatusRescheduled
	} else if retStatus == "FAILED" {
		status = StatusFailed
	} else if retStatus == "DOING" {
		status = StatusDoing
	} else {
		return -1, -1, fmt.Errorf("invalid status value: %s", retStatus)
	}

	if status == StatusFinished {
		retResult := ret["result"].(map[string]interface{})["result"].(map[string]interface{})["suggestion"].(string)
		if retResult == "block" {
			result = ResultBlock
		} else if retResult == "pass" {
			result = ResultPass
		} else if retResult == "review" {
			result = ResultReview
		} else {
			return -1, -1, fmt.Errorf("invalid result value: %s", retResult)
		}
	} else {
		result = -1
	}
	return
}
